package com.jiazhong.mingxing.project.bookstore.front.listener;

import com.alibaba.fastjson.JSONArray;
import com.alipay.api.AlipayApiException;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jiazhong.mingxing.project.bookstore.commons.bean.Alipay;
import com.jiazhong.mingxing.project.bookstore.commons.bean.Book;
import com.jiazhong.mingxing.project.bookstore.commons.bean.Stock;
import com.jiazhong.mingxing.project.bookstore.commons.mapper.StockMapper;
import com.jiazhong.mingxing.project.bookstore.front.config.SpringMVCConfig;
import com.jiazhong.mingxing.project.bookstore.front.service.impl.OrderServiceImpl;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.TransactionListener;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

@Slf4j
@Component
public class CheckStockListener implements TransactionListener {
    @Resource
    private StockMapper stockMapper;
    @Resource
    private RocketMQTemplate rocketMQTemplate2;

    private Object o;

    @SneakyThrows
    @Override
    public LocalTransactionState executeLocalTransaction(Message message, Object o) {
        log.info("message:{}", message);
        log.info("keys:{}", message.getKeys());
        log.info("o:{}", o);
        String orderId = message.getKeys().split(",")[0];
        String price = message.getKeys().split(",")[1];
        this.o = o;
        // 如果用户没有支付，UNKNOW
        AlipayTradeQueryRequest queryRequest = new AlipayTradeQueryRequest();
        Alipay alipay = new Alipay();
        // 需要一个订单号
        alipay.setOut_trade_no(orderId);
        String jsonString = JSONArray.toJSONString(alipay);
        queryRequest.setBizContent(jsonString);
        // 2. 执行并获取到结果
        String tradeStatus = "";
        try {
            AlipayTradeQueryResponse response = SpringMVCConfig.alipayClient.execute(queryRequest);
            tradeStatus = response.getTradeStatus();
            if (!Objects.equals(tradeStatus, "TRADE_SUCCESS")) {
                return LocalTransactionState.UNKNOW;
            }
            log.info("tradeStatus:{}", tradeStatus);
        } catch (AlipayApiException e) {
            log.info("tradeStatus:{}", tradeStatus);
            return LocalTransactionState.UNKNOW;
        }
        // 1. 产生查询请求并设置id
        // 校验库存是否充足
        log.info("开始校验库存是否充足");
        List<Book> bookList = JSONArray.parseArray(o.toString(), Book.class);
        for (Book book : bookList) {
            // 图书id
            String id = book.getId();
            // 购买数量
            int number = book.getNumber();
            // 查询库存中该本图书的数量
            QueryWrapper<Stock> wrapper = new QueryWrapper<>();
            wrapper.eq("book_id", id);
            Stock stock = stockMapper.selectOne(wrapper);
            int stockNumber = stock.getNumber();
            if (stockNumber < number) {
                log.info("库存不足");
                // 发送消息，撤销订单｜退款
                rocketMQTemplate2.syncSend("order:refund", message.getKeys());
                return LocalTransactionState.ROLLBACK_MESSAGE;
            }
        }
        log.info("库存充足");
        rocketMQTemplate2.syncSend("order:success", orderId + "*" + o.toString());
        return LocalTransactionState.COMMIT_MESSAGE;


    }

    @SneakyThrows
    @Override
    public LocalTransactionState checkLocalTransaction(MessageExt messageExt) {
        String orderId = messageExt.getKeys().split(",")[0];
        String price = messageExt.getKeys().split(",")[1];
        // 如果用户没有支付，UNKNOW
        AlipayTradeQueryRequest queryRequest = new AlipayTradeQueryRequest();
        Alipay alipay = new Alipay();
        // 需要一个订单号
        alipay.setOut_trade_no(orderId);
        String jsonString = JSONArray.toJSONString(alipay);
        queryRequest.setBizContent(jsonString);
        // 2. 执行并获取到结果
        String tradeStatus = "";
        try {
            AlipayTradeQueryResponse response = SpringMVCConfig.alipayClient.execute(queryRequest);
            tradeStatus = response.getTradeStatus();
            if (!Objects.equals(tradeStatus, "TRADE_SUCCESS")) {
                return LocalTransactionState.UNKNOW;
            }
            log.info("tradeStatus:{}", tradeStatus);
        } catch (AlipayApiException e) {
            log.info("tradeStatus:{}", tradeStatus);
            return LocalTransactionState.UNKNOW;
        }
        // 1. 产生查询请求并设置id
        // 校验库存是否充足
        log.info("开始校验库存是否充足");
        List<Book> bookList = JSONArray.parseArray(o.toString(), Book.class);
        for (Book book : bookList) {
            // 图书id
            String id = book.getId();
            // 购买数量
            int number = book.getNumber();
            // 查询库存中该本图书的数量
            QueryWrapper<Stock> wrapper = new QueryWrapper<>();
            wrapper.eq("book_id", id);
            Stock stock = stockMapper.selectOne(wrapper);
            int stockNumber = stock.getNumber();
            if (stockNumber < number) {
                log.info("库存不足");
                // 发送消息，撤销订单(orderId)｜退款(orderId和退款金额(price))
                rocketMQTemplate2.syncSend("order:refund", messageExt.getKeys());
                return LocalTransactionState.ROLLBACK_MESSAGE;
            }
        }
        log.info("库存充足");

        rocketMQTemplate2.syncSend("order:success", orderId);
        return LocalTransactionState.COMMIT_MESSAGE;
    }
}
